package simulation;

import java.util.Timer;
import java.util.TimerTask;

import maze.Location;
import maze.Maze;

public class PacmanPilot {
	private static double DIST_PER_TICK = 0.5;
	private static double ANGL_PER_TICK = 0.5;
	Timer timer = new Timer();
	
	private Simulator sim;
	private PacmanTravelTask moveTask;
	private PacmanRotateTask rotateTask;
	
	public PacmanPilot(Simulator simulator) {
		this.sim = simulator;
	}
	
	public void startTravel(boolean forward) {
		stop();
		
		moveTask = new PacmanTravelTask(forward);
		timer.schedule(moveTask, 0, 10);
	}
	
	public void startRotate(boolean clockwise) {
		stop();
		rotateTask = new PacmanRotateTask(clockwise);
		timer.schedule(rotateTask, 0, 10);
	}
	
	public void stop() {
		if(moveTask!=null) moveTask.cancel();
		if(rotateTask!=null) rotateTask.cancel();
	}

	class PacmanTravelTask extends TimerTask {

		private boolean forward;
		
		public PacmanTravelTask(boolean forward) {
			this.forward = forward;
		}

		@Override
		public void run() {
				Location pos = sim.getPacmanLocation();
				int ang = sim.getPacmanRotation();
				if ((float) Raycaster.cast(sim.getMaze(), pos, ang + (forward?0:180)) <= DIST_PER_TICK) {
					this.cancel();
					return;
				}
				
				pos.x += + (forward?1:-1) * (Math.cos(Math.toRadians(ang)) * DIST_PER_TICK);
				pos.y += + (forward?1:-1) * (Math.sin(Math.toRadians(ang)) * DIST_PER_TICK);
				
				sim.setPacmanLocation(pos);
		}	
	}
	
	class PacmanRotateTask extends TimerTask {

		private boolean counterclockwise;
		private double ang;
		
		public PacmanRotateTask(boolean clockwise) {
			this.counterclockwise = !clockwise;
			this.ang = sim.getPacmanRotation();
		}

		@Override
		public void run() {
				ang += (counterclockwise?1:-1)*ANGL_PER_TICK;
				sim.setPacmanRotation((int)ang);
		}	
	}
}
